package com.frame.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;

import com.frame.config.R;
import com.frame.config.ToDayWeatherConfig;
import com.frame.config.UploadMinioUtils;
import com.frame.domain.City;
import com.frame.domain.Retail;
import com.frame.imageprocess.strategy.ParsePicStrategy;
import com.frame.imageprocess.template.PicParseTemplate;
import com.frame.service.CityService;
import com.frame.service.RetailService;
import com.github.pagehelper.PageInfo;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.net.URLEncoder;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("retail")
public class RetailController extends PicParseTemplate {
    @Autowired
    private RetailService retailService;
    @Autowired
    private CityService cityService;



    @RequestMapping("getName")
    public Map<String,String>getName(String picType,String filepath){
        Map<String, String> map = new HashMap<>();
        if(picType.equals("businessLicense")){
            ParsePicStrategy businessLicense= super.processPic("businessLicense",filepath);
            map=businessLicense.parsePicSave(filepath);
        }else if(picType.equals("driverLicense")){
            ParsePicStrategy businessLicense= super.processPic("driverLicense",filepath);
            map=businessLicense.parsePicSave(filepath);
        }else if (picType.equals("idCard")){
            ParsePicStrategy businessLicense= super.processPic("idCard",filepath);
            map=businessLicense.parsePicSave(filepath);
        }
        return map;
    }


    @RequestMapping("cidBy")
    public R cidBy(String id){
       List<Retail> byId = retailService.city(id);
        return R.successed(byId);
    }
    @RequestMapping("byId")
    public R byId(Integer id){
        Retail retailById = retailService.getById(id);
        Retail retail = ToDayWeatherConfig.queryWeather(retailById.getCityName());
        System.out.println(retail);
        retail.setBid(id);
        retailService.updateById(retail);
        return R.successed(id);
    }
    
    @RequestMapping("imgText")
    public void imgText() throws TesseractException {
        File file = new File("E:\\pic\\666.jpg");
        System.out.println(file);
        Tesseract tesseract = new Tesseract();
        tesseract.setDatapath("E:\\zh");
        tesseract.setLanguage("chi_sim");
        String msg = tesseract.doOCR(file).replace("/n","").replace(" ","");
        int startIndex = msg.indexOf("名称") + "名称".length();
        int endIndex = msg.indexOf("注册资本");
        System.err.println(startIndex+"==="+endIndex);
        if(startIndex>0 && endIndex>0 && startIndex<endIndex){
            String name = msg.substring(startIndex, endIndex).trim();
            System.err.println("提取的名称:"+name);
        }else {
            System.out.println("无法提取名称信息");
        }
    }

    @RequestMapping("getTu")
    public List<Map<String,Object>> getTu(){
        List<Map<String,Object>>list=retailService.zList();
        return list;
    }
    @RequestMapping("import")
    public String selectRetail(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), Retail.class,new CellDataDemoHeadDataListenerRetail(retailService)).sheet().doRead();
        return "success";
    }
    //导出
    @RequestMapping("excel")
    public void excel(HttpServletResponse response) throws IOException {
        String fileName = URLEncoder.encode("零售信息", "UTF-8").replaceAll("\\+","%20");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.opnmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Retail> list = retailService.excellist();
        EasyExcel.write(response.getOutputStream(), Retail.class).sheet("零售信息").doWrite(list);

    }
    @RequestMapping("delete")
    public R delete(String id){
      boolean del= retailService.delete(id);
        return R.successed(del);
     }
     @RequestMapping("update")
     public R update(@RequestBody Retail retail){
         boolean update = retailService.update(retail);
         return R.successed(update);
     }
    @RequestMapping("upload")
    public String upload(MultipartFile file){
        String s = UploadMinioUtils.uploadPic(file);
        return s;
    }
    @RequestMapping("list")
    public R list(@RequestBody Retail retail,Integer pageNum,Integer pageSize){
        //处理时间
        String[] createTimes = retail.getCreateTimes();
        if(createTimes!=null && createTimes.length>0){
            retail.setStartTime(createTimes[0]);
            retail.setEndTime(createTimes[1]);
        }
        PageInfo<Retail>list=retailService.list(retail,pageNum,pageSize);
        return R.successed(list);
    }
    @RequestMapping("add")
    public R add(@RequestBody Retail retail){
        String snowflakeNextIdStr = IdUtil.getSnowflakeNextIdStr();
        System.err.println(snowflakeNextIdStr);
        retail.setShopId(snowflakeNextIdStr);
        boolean add = retailService.add(retail);
        return add?R.successed("成功"):R.failed("失败");
    }

    @RequestMapping("getTree")
    public R getTree(){
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        List<City> getlist = cityService.getlist();
        List<Tree<Object>> treeNodes = TreeUtil.<City, Object>build(getlist, 1, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCityId());
                    tree.setParentId(treeNode.getPid());
                    tree.setName(treeNode.getCityname());
                });
        return R.successed(treeNodes);
    }

}












